package connector;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import engine.HttpServletRequestImpl;
import engine.HttpServletResponseImpl;
import engine.ServletContextImpl;
import engine.servlet.HelloServlet;
import engine.servlet.IndexServlet;
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;


//实现AutoClosable接口，自动释放资源
public class HttpConnector implements HttpHandler,AutoCloseable {

    final Logger logger = LoggerFactory.getLogger(getClass());

    final ServletContextImpl servletContext;

    final HttpServer httpServer;
    final String host;
    final int port;

    public HttpConnector(String host, int port) throws IOException {
        this.host = host;
        this.port = port;

        this.servletContext = new ServletContextImpl();
        this.servletContext.initialize(List.of(IndexServlet.class, HelloServlet.class));

        //InetSocketAddress 对ip地址，端口号的封装
        this.httpServer = HttpServer.create(new InetSocketAddress(host,port),0);
        this.httpServer.createContext("/",this);
        this.httpServer.start();
        logger.info("http server launched at {}:{}",host,port);

    }




    @Override
    public void handle(HttpExchange exchange) throws IOException {
        logger.info("{}: {}?{}", exchange.getRequestMethod(), exchange.getRequestURI().getPath(), exchange.getRequestURI().getRawQuery());
        HttpExchangeAdapter adapter = new HttpExchangeAdapter(exchange);
        HttpServletRequest request = new HttpServletRequestImpl(adapter);
        HttpServletResponse response = new HttpServletResponseImpl(adapter);

        try {
            this.servletContext.process(request, response);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

    }

    @Override
    public void close() throws Exception {
        this.httpServer.stop(3);
        logger.info("http server shutdown in 3s");
    }



}
